package orz.mikeneck.server.locrec.model;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import orz.mikeneck.server.locrec.exception.LocRecUserNotFoundException;
import orz.mikeneck.server.locrec.persistent.LocRecUser;

public class LocRecUserModelImpl implements LocRecUserModel {

	private String email;

	private PersistenceManager manager;

	private Query query;

	@Override
	public LocRecUserModel emailIs(String email) {
		this.email = email;
		return this;
	}

	@Override
	public LocRecUserModel persistenceManagerIs(PersistenceManager manager) {
		this.manager = manager;
		return this;
	}

	@Override
	public LocRecUserModel createSearchQuery(){
		query = createDefaultQuery();
		return this;
	}

	@Override
	public Query createDefaultQuery(){
		Query q = createBaseQuery();
		q.setFilter(FILTER);
		q.declareParameters(PARAMS);
		return q;
	}

	@Override
	public Query createBaseQuery(){
		return manager.newQuery(LocRecUser.class);
	}

	@Override
	public Query createAdminQuery(){
		Query q = createBaseQuery();
		q.setOrdering(ORDER);
		return q;
	}

	@Override
	public LocRecUserModel createCountQuery(){
		query = createDefaultQuery();
		query.setResult(COUNT);
		return this;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LocRecUser> findLocRecUser() throws LocRecUserNotFoundException {
		List<LocRecUser> result;
		result = (List<LocRecUser>) query.execute(email);
		if(result.size() > 0){
			return result;
		}else{
			throw new LocRecUserNotFoundException(email);
		}
	}

	@Override
	public LocRecUser getLocRecUser() throws LocRecUserNotFoundException {
		return findLocRecUser().get(0);
	}

	@Override
	public int getUserCount() {
		return (Integer) query.execute(email);
	}

	@Override
	public boolean isUserExisting() {
		return getUserCount() > 0;
	}
}
